package com.ym521.emojipack.install;

import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import com.ym521.emojipack.EmojiPackHelper;
import com.ym521.emojipack.emoji.EmojiPackHandler;

/**
 * @author Ym
 */
public final class EmojiPackTextWatcher implements TextWatcher {
    static final int START_DEFAULT = -1;
    static final int START_SKIP_TEXT_WATCHER = -2;
    private TextView mTextView;
    private final EmojiPackHelper.Builder builder;
    private int start = START_DEFAULT;

    public EmojiPackTextWatcher(TextView textView, EmojiPackHelper.Builder builder) {
        this.mTextView = textView;
        this.builder = builder;

        if (!TextUtils.isEmpty(textView.getText())) {
            if (textView instanceof EditText) {
                EditText editText = (EditText) textView;
                updateText(editText.getText());
            } else {
                Editable text = new SpannableStringBuilder(textView.getText());
                updateText(text);
                mTextView.setText(text);
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (this.start == START_SKIP_TEXT_WATCHER) return;
        if (this.start == START_DEFAULT && count > 0) {
            this.start = start;
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (start >= 0) {
            start = START_SKIP_TEXT_WATCHER;
            updateText(editable);
            start = START_DEFAULT;
        }
    }

    private void updateText(Editable editable) {
        float textSize = mTextView.getTextSize();
        //默认放大 20%
        float packSize = textSize * EmojiPackHelper.Builder.EMOJI_ENLARGE;
        EmojiPackHandler.addEmojis(mTextView.getContext(), editable,
                (int) packSize, builder.alignment, (int) textSize);
    }
}
